package moltencore.network.game.strategy;

import moltencore.config.Config;
import moltencore.game.Game;
import moltencore.game.Player;
import moltencore.network.game.GameLobby;
import moltencore.network.game.exception.FullGameException;
import moltencore.network.game.exception.JoinTeamException;
import moltencore.network.protocol.JoinGame;
import moltencore.network.protocol.JoinGameResponse;
import moltencore.network.protocol.JoinTeam;
import moltencore.network.protocol.PlayerData;
import moltencore.player.exception.PlayerAlreadyRegisteredException;
import moltencore.player.exception.PlayerNameAlreadyExistsException;
import org.apache.log4j.Logger;
import spark.network.protocol.Acknowledgement;
import spark.network.protocol.Base;
import spark.network.protocol.Response;
import spark.network.strategy.IProtocolHandleStrategy;
import spark.utility.OutWrapper;

import java.util.Collection;

public class JoinTeamStrategy implements IProtocolHandleStrategy<JoinTeam> {
	private Logger logger = Logger.getLogger(JoinTeamStrategy.class);

	private GameLobby lobby;

	public JoinTeamStrategy(GameLobby lobby) {
		this.lobby = lobby;
	}

	@Override
	public void handle(JoinTeam packet, OutWrapper<Response> acknowledgement, Collection<Base> additionalData) {
		try {
			if(packet.getTeamIndex() == -1) {
				logger.info("Player " + packet.getSession() + " tries to join spectators");
				lobby.playerJoinSpectators(packet.getSession());
			}
			else {
				logger.info("Player " + packet.getSession() + " tries to join team " + packet.getTeamIndex() + " and slot " + packet.getSlotIndex());
				lobby.playerJoinTeam(packet.getSession(), packet.getTeamIndex(), packet.getSlotIndex());
			}
		}
		catch(JoinTeamException e) {
			logger.warn("Player " + packet.getSession() + " tried to join invalid team join", e);
		}
		acknowledgement.value = new Acknowledgement(packet);
	}
}